package net.topicopedia.servlets.topics;
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class CreateUserTopicServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		      throws IOException {
		    System.out.println("Creating new todo ");
		    
		    String userId = req.getParameter("user");
		    String topicId = req.getParameter("topic");
		    
		    Key userKey = KeyFactory.createKey("User", (Long) Long.parseLong(userId) );
		    Key topicKey = KeyFactory.createKey("Topic", (Long) Long.parseLong(topicId) );
		    
		    Entity topic = new Entity("UserTopic");
		    topic.setProperty("user", userKey);
		    topic.setProperty("topic", topicKey);
		    topic.setProperty("items", new Text( req.getParameter("items")) );
		    topic.setProperty("references", new Text( req.getParameter("references") ) );
		    
		    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		    
			topicKey = datastore.put( topic );
			
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setContentType("text/plain");
			
			resp.getWriter().println(String.valueOf( topic.getProperty("topic") ));
			resp.getWriter().println(" userTopic id :: " + topicKey.getId() );
	}

}
 